﻿using System.IO;
using System.Text;

namespace GameView.Comment
{
    public static class SecureStorage
    {
        private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("Xiasjd23ASasd89@*");

        public static string Save(string key, string value)
        {
            //var encryptedData = ProtectedData.Protect(
            //    Encoding.UTF8.GetBytes(value),
            //    Entropy,
            //    DataProtectionScope.CurrentUser);

            var kk = GetFilePath(key);
            var rra = Encoding.UTF8.GetBytes(value.Encrypt());
            File.WriteAllBytes(kk, rra);
            return kk;
        }

        public static string Load(string key)
        {
            try
            {
                var encryptedData = File.ReadAllBytes(GetFilePath(key));
                var ss = Encoding.UTF8.GetString(encryptedData);
                return ss.Decrypt();
            }
            catch
            {
                return null;
            }
        }

        public static void Delete(string key)
        {
            try
            {
                if (key == "a;ll")
                {
                    var appData = AppDomain.CurrentDomain.BaseDirectory;
                    //appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    var directoryPath = Path.Combine(appData, "GameView");
                    if (!Directory.Exists(directoryPath))
                    {
                        return;
                    }
                    DirectoryInfo directory = new DirectoryInfo(directoryPath);
                    foreach (FileInfo file in directory.GetFiles())
                    {
                        file.Delete();
                    }
                }
                File.Delete(GetFilePath(key));
            }
            catch { }
        }

        private static string GetFilePath(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return string.Empty;
            }
            var appData = System.IO.Directory.GetCurrentDirectory();
            var directoryPath = Path.Combine(appData, "Config");

            // 确保目录存在
            if (!Directory.Exists(directoryPath))
            {
                var dir = Directory.CreateDirectory(directoryPath);
                dir.Attributes = FileAttributes.Hidden;
            }

            return Path.Combine(directoryPath, $"{key}.dat");
        }
    }
}